//
//  GFSearchResturtantViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFSearchResturtantViewController.h"


@interface GFSearchResturtantViewController ()<UISearchBarDelegate, UISearchResultsUpdating , UISearchControllerDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIView *viewForSearch;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, assign) NSInteger cityId;
@property (nonatomic, strong) NSMutableArray *arrayForRegion;
@property (nonatomic, strong) NSMutableArray *arrayForCate;
@property (nonatomic, strong) UILabel *CateLabel;
@property (nonatomic, strong) UILabel *regionLabel;
@property (nonatomic, strong) UIButton *CateButton;
@property (nonatomic, strong) UIButton *regionButton;
@property (nonatomic, strong) CAKeyframeAnimation *keyFrame;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, assign) NSInteger countForCate;
@property (nonatomic, assign) BOOL animationStartOrFinish;
@property (nonatomic, strong) NSTimer *timerForCate;
@property (nonatomic, strong) NSTimer *timerForRegion;
@property (nonatomic, strong) UITableView *tableViewForSearchResult;
@property (nonatomic, strong) NSMutableArray *arrayForSearchResult;
@property (nonatomic, strong) NSMutableArray *attributeArray;
@property (nonatomic, copy) NSString *cateName;
@property (nonatomic, copy) NSString *regionId;
@property (nonatomic, copy) NSString *regionName;

@end

@implementation GFSearchResturtantViewController
#pragma mark - 导航
- (void)viewForNavi {
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    view.backgroundColor = [UIColor redColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2, ScreenHeight / 3, ScreenWidth / 3, ScreenHeight / 4)];
    label.text = @"搜索";
    label.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    self.view.backgroundColor = [UIColor lightGrayColor];

}
#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.cateName = @"";
    self.regionId = @"";
    self.regionName = @"";
}
#pragma mark - 试图加载
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.cityId = 3;
    self.count = 0;
    [self.waitView removeFromSuperview];
    [self viewForNavi];
    [self createSearchController];
    [self creatTableView];
//    [self.view bringSubviewToFront:self.waitView];
    [self handleData];
    
    self.view.backgroundColor = [UIColor whiteColor];
//    [self removeButtonLayout:self.viewForSearch];
    
}
#pragma mark - 解析数据
- (void)handleData {
    self.arrayForRegion = [NSMutableArray array];
    self.arrayForCate = [NSMutableArray array];
    NSLog(@"%@",self.city_id);
    NSString *url = [NSString stringWithFormat:@"http://api.meishixing.com/other/top/hot_region_and_food/city_id=%ld", [self.city_id integerValue]];
    [AFNetHandle GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:result];
        NSDictionary *dic = [dictionary objectForKey:@"result"];
        GFSearchResturtantModel *model = [GFSearchResturtantModel modWithDic:dic];
        NSArray *arr = (NSArray *)model.hot_region;
        NSArray *arrCate = (NSArray *)model.hot_food_category;
        for (NSDictionary *dic in arrCate) {
            [self.arrayForCate addObject:dic];
        }
            for (NSDictionary *dic in arr) {
                [self.arrayForRegion addObject:dic];
    
            }
        if (self.arrayForCate.count != 0) {
            [self createLabel];
            [self createButton];
        }
        if (self.arrayForRegion.count > 3) {
            NSArray *array = [self randWithArray:self.arrayForRegion];
            for (int i = 0; i < 3; i ++) {
                UIButton *button = (UIButton *)[self.view viewWithTag:1000+i];
                [button setTitle:[array[i] objectForKey:@"region_name"] forState:0];
            }
        }

            
//        [self.waitView removeFromSuperview];
    } fail:^(NSError *error) {
//        [self.waitView removeFromSuperview];
    }];
}
#pragma mark - 创建searchController
- (void)createSearchController {
  
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.delegate = self;
    self.searchController.searchBar.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.placeholder = @"请输入要搜索的餐馆";
//    self.searchController.dimsBackgroundDuringPresentation = NO;
//    self.searchController.searchBar.backgroundColor = [UIColor redColor];
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    self.viewForSearch = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.size.height, ScreenWidth, ScreenHeight / 20)];
//    self.viewForSearch.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.viewForSearch];
    [self.viewForSearch addSubview:self.searchController.searchBar];
    [self.searchController.searchBar sizeToFit];
    self.searchController.view.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 点击搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    GFResultViewController *resultVc = [[GFResultViewController alloc] initWithKey:searchBar.text withRegionId:self.regionId withCate:self.cateName withCityId:self.cityId withRegionName:self.regionName];
    
    [self.navigationController pushViewController:resultVc animated:1];
    [self.searchController setActive:0];
}
#pragma mark - 搜索更新的代理
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    [self handleDataForSearchResult];
    

}

#pragma mark - 移除background
- (void)removeButtonLayout:(UIView *)current {
    
    if ([current isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        
        [current removeFromSuperview];
        
    } else if ([current isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
        current.backgroundColor = [UIColor colorWithRed:0.000 green:0.129 blue:0.264 alpha:1.000];
        UITextField *textField = (UITextField *)current;
        
        textField.textColor = [UIColor groupTableViewBackgroundColor];
        
    }
    for (UIView *view in current.subviews) {
        [self removeButtonLayout:view];
    }
}
#pragma mark - 创建label
- (void)createLabel {
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    if (self.arrayForRegion.count >3) {
        self.regionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, view.frame.size.height + ScreenHeight / 20 + 20, ScreenWidth, ScreenHeight / 20)];
        self.regionLabel.text = @"热门区域";
        [self.view addSubview:self.regionLabel];
    }
    
    if (self.arrayForCate.count > 4) {
        self.CateLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, view.frame.size.height + ScreenHeight / 10 + 30 + ScreenHeight / 30, ScreenWidth, ScreenHeight / 20)];
        self.CateLabel.text = @"热门菜系";
        [self.view addSubview:self.CateLabel];
    }
  
}
#pragma mark - 创建button
- (void)createButton {
    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    if (self.arrayForRegion.count > 3) {
        for (int i = 0; i < 3; i ++) {
            
            self.regionButton = [UIButton buttonWithType:UIButtonTypeSystem];
            self.regionButton.frame = CGRectMake(5 + ((ScreenWidth - 20) / 3 + 5) * i, view.frame.size.height + ScreenHeight / 10 + 25, (ScreenWidth - 20) / 3, ScreenHeight / 30);
            self.regionButton.layer.masksToBounds = YES;
            self.regionButton.layer.cornerRadius = 5;
            self.regionButton.tag = 1000 +i;
            [self.view addSubview:self.regionButton];
            self.regionButton.titleLabel.font = [UIFont systemFontOfSize:12];
            [self.regionButton setTintColor:[UIColor blackColor]];
            self.regionButton.backgroundColor = [UIColor cyanColor];
            [self.regionButton addTarget:self action:@selector(region:) forControlEvents:UIControlEventTouchUpInside];
        }
        self.timerForRegion = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timeForRegion:) userInfo:nil repeats:1];
    }
    
    if (self.arrayForCate.count > 4) {
        self.countForCate = 4;
        for (int i = 0; i < 4; i ++) {
            self.CateButton = [UIButton buttonWithType:UIButtonTypeSystem];
            self.CateButton.frame = CGRectMake(5 + ((ScreenWidth - 20) / 3 + 5) * i, view.frame.size.height + ScreenHeight / 10 + 35 + ScreenHeight / 30 + ScreenHeight / 20, (ScreenWidth - 20) / 3, ScreenHeight / 30);
            self.CateButton.layer.masksToBounds = YES;
            self.CateButton.layer.cornerRadius = 5;
            self.CateButton.tag = 2000 + i;
            [self.view addSubview:self.CateButton];
            self.CateButton.titleLabel.font = [UIFont systemFontOfSize:12];
            [self.CateButton setTintColor:[UIColor blackColor]];
            self.CateButton.backgroundColor = [UIColor orangeColor];
            [self.CateButton setTitle:[NSString stringWithFormat:@"%d",i] forState:0];
            [self.CateButton addTarget:self action:@selector(cate:) forControlEvents:UIControlEventTouchUpInside];
            [self.CateButton setTitle:[[self.arrayForCate objectAtIndex:i] objectForKey:@"category_name"]forState:0];
        }
        self.timerForCate = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(time:) userInfo:nil repeats:1];
    }


    
}
#pragma mark - 定时器方法cate
- (void)time:(NSTimer *)timer {
    
    [self keyAnimationForLabel];
    

}
#pragma mark - 定时器方法region
- (void)timeForRegion:(NSTimer *)timer {
    if (self.arrayForRegion.count > 3) {
        NSArray *array = [self randWithArray:self.arrayForRegion];
        for (int i = 0; i < 3; i ++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:1000+i];
            [button setTitle:[array[i] objectForKey:@"region_name"] forState:0];
        }
    }
}
#pragma mark - regionButton 点击
- (void)region:(UIButton *)button {
    self.regionName = button.titleLabel.text;
    for (NSDictionary *dic in self.arrayForRegion) {
        if ([[dic objectForKey:@"region_name"] isEqualToString:button.titleLabel.text]) {
            self.regionId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"region_id"]];
            GFResultViewController *resultVc = [[GFResultViewController alloc] initWithKey:self.searchController.searchBar.text withRegionId:self.regionId withCate:self.cateName withCityId:self.cityId withRegionName:self.regionName];
            [self.navigationController pushViewController:resultVc animated:1];
        }
    }
}
#pragma Catebutton 点击
- (void)cate:(UIButton *)button {
    self.cateName = button.titleLabel.text;
    GFResultViewController *resultVc = [[GFResultViewController alloc] initWithKey:self.searchController.searchBar.text withRegionId:self.regionId withCate:self.cateName withCityId:self.cityId withRegionName:self.regionName];
    [self.navigationController pushViewController:resultVc animated:1];

}
#pragma mark - key动画
- (void)keyAnimationForLabel {
    

    UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
    for (int i = 0; i < 4; i ++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:2000 + i];
        
        self.keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        self.keyFrame.delegate = self;
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, button.center.x , button.center.y);
        
        CGPathAddLineToPoint(path, NULL, button.center.x - (5 + (ScreenWidth-20)/3) , button.center.y);
        
        self.keyFrame.path = path;
        
        self.keyFrame.duration = 2;
        self.keyFrame.autoreverses = 0;
        self.keyFrame.repeatCount = 0;
        

        [button.layer addAnimation:self.keyFrame forKey:@"key"];
        
//        NSLog(@"%@",pa.)
    }


}
#pragma mark - 根据动画开始还是结束让button启用或者不启用
- (void)buttonIsEnabled:(BOOL)switchAnimation {
    for (int i = 0; i < 4; i ++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:2000 + i];
        if (switchAnimation) {
            
            [button removeTarget:self action:@selector(cate:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [button addTarget:self action:@selector(cate:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
    }
}
#pragma mark - 动画开始
- (void)animationDidStart:(CAAnimation *)anim {
    self.animationStartOrFinish = YES;
    [self buttonIsEnabled:self.animationStartOrFinish];
}
#pragma mark - 动画结束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {

    if (self.animationStartOrFinish) {
        for (int i = 0; i < 4; i ++) {
            UIView *view = (UIView *)[self.navigationController.view viewWithTag:10001];
            UIButton *button = (UIButton *)[self.view viewWithTag:2000 + i];
            if (button.tag - 2000 == self.count) {
                button.frame = CGRectMake(5 + ((ScreenWidth - 20) / 3 + 5) * 3 , view.frame.size.height + ScreenHeight / 10 + 35 + ScreenHeight / 30 + ScreenHeight / 20, (ScreenWidth - 20) / 3, ScreenHeight / 30);
                [button setTitle:[self.arrayForCate[self.countForCate] objectForKey:@"category_name"] forState:0];
            } else {
                if (i >= (self.count + 1)) {
                    button.frame = CGRectMake(5 + ((ScreenWidth - 20) / 3 + 5) * (i - 1 - self.count), view.frame.size.height + ScreenHeight / 10 + 35 + ScreenHeight / 30 + ScreenHeight / 20, (ScreenWidth - 20) / 3, ScreenHeight / 30);
                    
                } else {
                    button.frame = CGRectMake(5 + ((ScreenWidth - 20) / 3 + 5) * (3 - self.count + i ) , view.frame.size.height + ScreenHeight / 10 + 35 + ScreenHeight / 30 + ScreenHeight / 20, (ScreenWidth - 20) / 3, ScreenHeight / 30);
                }
                
            }
            
        }
        self.countForCate ++;
        if (self.countForCate == self.arrayForCate.count) {
            self.countForCate = 0;
        }
        self.count ++;
        if (4 == self.count) {
            self.count = 0;
        }
    }
    
    self.animationStartOrFinish = NO;
    [self buttonIsEnabled:self.animationStartOrFinish];

}
#pragma mark - 随机数生成
- (NSArray *)randWithArray:(NSMutableArray *)array {
    if (array.count != 0) {
        NSMutableArray *arr1 = [NSMutableArray array];
        NSMutableArray *arr2 = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < array.count; i ++) {
            [arr1 addObject:array[i]];
        }
        for (int i = 0; i < 3; i ++) {
            NSInteger ran = arc4random()%arr1.count;
            [arr2 addObject:arr1[ran]];
            arr1[ran]= [arr1 lastObject];
            [arr1 removeLastObject];
        }
        
        return arr2;
    } else {
        return nil;
    }

}

#pragma mark - 创建查询结果的tableView
- (void)creatTableView {
    self.tableViewForSearchResult = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, 300) style:UITableViewStylePlain];
    self.tableViewForSearchResult.delegate = self;
    self.tableViewForSearchResult.dataSource = self;
    [self.tableViewForSearchResult registerClass:[UITableViewCell class] forCellReuseIdentifier:@"search"];
    self.tableViewForSearchResult.bounces = NO;
    self.tableViewForSearchResult.tableFooterView = [[UIView alloc] init];
    self.tableViewForSearchResult.separatorInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [self.searchController.view addSubview:self.tableViewForSearchResult];
    
}
#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.arrayForSearchResult.count != 0) {
        NSString *str = [[self.arrayForSearchResult objectAtIndex:indexPath.row] query_log_name];
        NSMutableAttributedString *ats = [[NSMutableAttributedString alloc] initWithString:str attributes:nil];
        if (self.searchController.searchBar.text.length > 0) {
            
            NSMutableArray *arrForModelName = [NSMutableArray array];
            NSMutableArray *arrName = [NSMutableArray array];
            for (int i = 0; i < str.length; i ++) {
                NSRange range = {static_cast<NSUInteger>(i),1};
                [arrForModelName addObject:[str substringWithRange:range]];
            }
            for (int i = 0; i < self.searchController.searchBar.text.length; i ++) {
                NSRange range = {static_cast<NSUInteger>(i),1};
                [arrName addObject:[self.searchController.searchBar.text substringWithRange:range]];
            }
            for (int i = 0; i < arrForModelName.count; i ++) {
                for (int j = 0; j < arrName.count; j ++) {
                    if ([arrName[j] isEqualToString:arrForModelName[i]] || [[arrName[j] capitalizedString] isEqualToString:arrForModelName[i]] ||[arrName[j] isEqualToString:[arrForModelName[i] capitalizedString]]) {
                        [ats setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:20]} range:NSMakeRange(i, 1)];
                    }
                }
            }
            
        }
        cell.textLabel.attributedText = ats;
        //            cell.textLabel.text = [[self.arrayForSearchResult objectAtIndex:indexPath.row] query_log_name];
    }
    return cell;
}
#pragma mark - row number
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([self.searchController.searchBar.text isEqualToString:@""]) {
        return 0;
    } else {
        return self.arrayForSearchResult.count;
    }
    
    
    
}
#pragma mark - 解析实时搜索结果数据
- (void)handleDataForSearchResult {
    self.arrayForSearchResult = [NSMutableArray array];
//    self.attributeArray = [NSMutableArray array];
    NSString *url = [NSString stringWithFormat:@"http://api.meishixing.com/search/suggest/query_log/keyword=%@&city_id=%ld", self.searchController.searchBar.text, [self.city_id integerValue]];
    [AFNetHandle GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:result];
        NSArray *arr = [dictionary objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            GFSearchResultModel *model = [GFSearchResultModel modWithDic:dic];
            [self.arrayForSearchResult addObject:model];
        }
            [self.tableViewForSearchResult reloadData];
        
        
    } fail:^(NSError *error) {

    }];
}

#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        return 30;
    
    
}
#pragma mark - 点击tableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    GFResultViewController *resultVc = [[GFResultViewController alloc] initWithKey:cell.textLabel.text withRegionId:self.regionId withCate:self.cateName withCityId:[self.city_id integerValue] withRegionName:self.regionName];
    
    [self.navigationController pushViewController:resultVc animated:1];
    [self.searchController setActive:0];
    
}
@end
